package com.itcy7.service;

import com.itcy7.entity.BackendUser;
import com.itcy7.utils.dto.LoginDto;
import com.itcy7.utils.session.SessionUtils;
import com.itcy7.utils.vo.LoginVo;
import com.itcy7.dao.BackendUserDao;
import com.itcy7.dao.DevUserDao;
import com.itcy7.entity.DevUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class LoginService {

    @Autowired
    BackendUserDao backendUserDao;

    @Autowired
    DevUserDao devUserDao;

    public LoginVo loginOn(LoginDto loginDto) {
        LoginVo loginVo=null;

        if(loginDto.getType()==1){
            BackendUser backendUser=new BackendUser();
            backendUser.setUsercode(loginDto.getAccount());
            backendUser.setUserpassword(loginDto.getPassword());
            List<BackendUser> backendUserList = backendUserDao.queryAll(backendUser);
            if(backendUserList==null || backendUserList.size()==0){
                throw new RuntimeException("账号密码错误");
            }
            backendUser.setUsername(backendUserList.get(0).getUsername());
            backendUser.setId(backendUserList.get(0).getId());

            StringBuilder sb=new StringBuilder();
            sb.append(UUID.randomUUID().toString().replace("-","")+"-");
            sb.append(backendUserList.get(0).getUsercode()+"-");
            sb.append(backendUserList.get(0).getId());
            sb.append("-admin-");
            sb.append(System.currentTimeMillis());
            SessionUtils.setToken(sb.toString(),backendUser);
            loginVo=new LoginVo(sb.toString(),backendUser,loginDto.getType());
        }else if(loginDto.getType()==0){
            DevUser devUser=new DevUser();
            devUser.setDevcode(loginDto.getAccount());
            devUser.setDevpassword(loginDto.getPassword());
            List<DevUser> devUserList = devUserDao.queryAll(devUser);
            if(devUserList==null || devUserList.size()==0){
                throw new RuntimeException("账号密码错误");
            }
            devUser.setDevname(devUserList.get(0).getDevname());
            devUser.setId(devUserList.get(0).getId());

            StringBuilder sb=new StringBuilder();
            sb.append(UUID.randomUUID().toString().replace("-","")+"-");
            sb.append(devUserList.get(0).getDevcode()+"-");
            sb.append(devUserList.get(0).getId());
            sb.append("-dev-");
            sb.append(System.currentTimeMillis());
            SessionUtils.setToken(sb.toString(),devUser);
            loginVo=new LoginVo(sb.toString(),devUser,loginDto.getType());
        }
        return loginVo;
    }
}
